﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using NewLife.Messaging;
using XingLucifer.IBase.Enums;
using XCode.Membership;
using System.IO;
using Kinlo.WebApi.Controllers;
using Kinlo.WebApi.Model;
using System.Security.Cryptography;
using System.Text.Json;
using Kinlo.Entitys;

namespace Kinlo.WebApi
{
    public class Startup
    {
         Action<string, MessageLevelType> _log;

        DateTime startTime { get; set; }=DateTime.Now;
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                startTime=DateTime.Now;
                //_log = log;
                services.AddControllers();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
           
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Action<string, MessageLevelType> log)
        {
            try
            {
                _log=log;
               
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseRouting();

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapGet("/", async context =>
                    {
                        await context.Response.WriteAsync("Hello World!");
                    });

                    endpoints.MapPost("/api/plate/reqplate", async delegate (HttpContext context)
                    {
                        using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8))
                        {
                            OCV.Meta.TableName = $"OCV_{startTime:yyyy}{GetQuarterly(startTime)}";
                            Precharge.Meta.TableName = $"Precharge_{startTime:yyyy}{GetQuarterly(startTime)}";
                            Plate.Meta.TableName = $"Plate_{startTime:yyyy}{GetQuarterly(startTime)}";


                            string jsonstring = await reader.ReadToEndAsync();
                            PlateRequest req = System.Text.Json.JsonSerializer.Deserialize<PlateRequest>(jsonstring);

                            PlateDatas plateDatas = new PlateDatas(_log);
                           var rsp=plateDatas.Get(req);

                            // 将结果写入响应
                            await context.Response.WriteAsync(JsonSerializer.Serialize(rsp));
                            // 在这里处理jsonstring，例如反序列化为PlateRequest对象
                            //await context.Response.WriteAsync("Hello World!");

                        }
                    });
                    endpoints.MapPost("/api/plate/uploadinfo", async delegate (HttpContext context)
                    {
                        using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8))
                        {
                            OCV.Meta.TableName = $"OCV_{startTime:yyyy}{GetQuarterly(startTime)}";
                            Precharge.Meta.TableName = $"Precharge_{startTime:yyyy}{GetQuarterly(startTime)}";
                            Plate.Meta.TableName = $"Plate_{startTime:yyyy}{GetQuarterly(startTime)}";

                            string jsonstring = await reader.ReadToEndAsync();
                            PrechargeDto req = System.Text.Json.JsonSerializer.Deserialize<PrechargeDto>(jsonstring);

                            PlateDatas plateDatas = new PlateDatas(_log);
                           var rsp=plateDatas.AddPrechargeOCVData(req);

                            // 将结果写入响应
                            await context.Response.WriteAsync(JsonSerializer.Serialize(rsp));
                            // 在这里处理jsonstring，例如反序列化为PlateRequest对象
                            //await context.Response.WriteAsync("Hello World!");

                        }
                    });
                    endpoints.MapPost("/api/plate/reqocv", async delegate (HttpContext context)
                    {
                        using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8))
                        {
                            OCV.Meta.TableName = $"OCV_{startTime:yyyy}{GetQuarterly(startTime)}";
                            Precharge.Meta.TableName = $"Precharge_{startTime:yyyy}{GetQuarterly(startTime)}";
                            Plate.Meta.TableName = $"Plate_{startTime:yyyy}{GetQuarterly(startTime)}";

                            string jsonstring = await reader.ReadToEndAsync();
                            OCVRequest req = System.Text.Json.JsonSerializer.Deserialize<OCVRequest>(jsonstring);

                            PlateDatas plateDatas = new PlateDatas(_log);
                           var rsp=plateDatas.GetOCV(req);

                            // 将结果写入响应
                            await context.Response.WriteAsync(JsonSerializer.Serialize(rsp));
                            // 在这里处理jsonstring，例如反序列化为PlateRequest对象
                            //await context.Response.WriteAsync("Hello World!");

                        }
                    });


                    //endpoints.MapControllers();
                });
            }catch(Exception ex)
            {
                _log.Invoke($"77777777{ex}", MessageLevelType.警告);
                Console.WriteLine(ex.ToString());
            }
          
        }
        public static int GetQuarterly(DateTime dateTime) => dateTime.Month switch
        {
            int p when p is >= 1 and < 4 => 1,
            int p when p is >= 4 and < 7 => 2,
            int p when p is >= 7 and < 10 => 3,
            int p when p is >= 10 and <= 12 => 4,
            _ => 1,
        };

    }
}
